﻿using System.Linq;
using System.Web.Mvc;
using cludg.Infrastructure.Core.Logging;

namespace cludg.Web.Core.ViewEngines
{
    public class WebFormsViewEngineProvider : IViewEngineProvider
    {
        public WebFormsViewEngineProvider(ILogger logger)
        {
            Logger = logger;
        }

        static readonly string[] DisabledFormats = new[] { "~/Disabled" };

        public ILogger Logger { get; set; }

        public IViewEngine CreateModulesViewEngine(CreateModulesViewEngineParams parameters)
        {
            var areaFormats = new[] {
                                        "~/Core/{2}/Views/{1}/{0}.ascx",
                                        "~/Core/{2}/Views/{1}/{0}.aspx",
                                        "~/Modules/{2}/Views/{1}/{0}.ascx",
                                        "~/Modules/{2}/Views/{1}/{0}.aspx",
                                    };

            Logger.DebugFormat("AreaFormats (module): \r\n\t-{0}", string.Join("\r\n\t-", areaFormats));

            var universalFormats = parameters.VirtualPaths
                .SelectMany(x => new[] {
                                           x + "/Views/{1}/{0}.ascx",
                                           x + "/Views/{1}/{0}.aspx",
                                           x + "/Views/Shared/{0}.aspx",
                                           x + "/Views/Shared/{0}.ascx",
                                       })
                .ToArray();

            Logger.DebugFormat("UniversalFormats (module): \r\n\t-{0}", string.Join("\r\n\t-", universalFormats));

            var viewEngine = new WebFormViewEngine
            {
                MasterLocationFormats = DisabledFormats,
                ViewLocationFormats = universalFormats,
                PartialViewLocationFormats = universalFormats,
                AreaMasterLocationFormats = DisabledFormats,
                AreaViewLocationFormats = areaFormats,
                AreaPartialViewLocationFormats = areaFormats,
            };

            return viewEngine;
        }
    }
}
